<template>
    <van-row>
      <van-col span="16">
        <van-button :color= "btnColor" block @click="openDoor" :disabled="isOpening">{{ doorButtonLabel }}</van-button>
      </van-col>
      <!-- <van-col span = "8"> <p>{{ doorStatus }}</p>  </van-col> -->
      <van-col span="8"><img :src="doorImage" class="door-image" alt="Door Status" /> </van-col>
    </van-row>
</template>
    
<script setup name="DoorComponent">
    import {
      ref,
      onMounted,
      onUnmounted
    } from 'vue';
    import service from "@/utils/request"; // 用于发送HTTP请求  
    import {
      showSuccessToast
    } from 'vant';
    const props = defineProps({
      doorName: {
        type: String,
        default: 'Door'
      },
      doorUrl: {
        type: String,
        required: true
      },
      openImg: {
        type: String,
        required: false
      },
      closeImg: {
        type: String,
        required: false
      },
      btnColor: {
        type: String,
        default: "#72eefd",
        required: false
      }
    });
    const doorStatus = ref('closed'); // 初始状态为关闭  
    const doorButtonLabel = ref(`开${props.doorName}`);
    const doorImage = ref(props.closeImg); // 初始图片为关闭的门  
    const isOpening = ref(false); // 防止多次点击按钮 
    // 假设您有一个根据状态返回图像路径的方法  
    // const doorImagePath = computed(() => doorStatus.value === 'open' ? '/path/to/open-door.png' : '/path/to/closed-door.png');  
    let timerId = null; // 用于设置定时器  
    const openDoor = async() => {
      if (isOpening.value) return; // 如果正在打开，则不重复点击  
      isOpening.value = true; // 标记为正在打开  
      try {
        // 模拟后端开门API调用，实际中您需要替换为真实的API地址和参数  
        await service.get(props.doorUrl);
        showSuccessToast(props.doorName + "已打开")
        doorStatus.value = 'open'; // 门已打开  
        // 您可以在这里更新 doorImagePath 或其他相关状态  
        doorButtonLabel.value = `关${props.doorName}`;
        doorImage.value = props.openImg; // 切换到已打开的图片  
        timerId = setTimeout(() => {
          showSuccessToast({
            message: props.doorName + "已关闭",
            icon: props.closeImg,
          })
          doorStatus.value = 'closed'; // 5秒后门已关闭  
          // 您可以在这里恢复 doorImagePath 或其他相关状态  
          doorButtonLabel.value = `开${props.doorName}`;
          doorImage.value = props.closeImg; // 切换到已关闭的图片  
          isOpening.value = false; // 清除打开状态标记  
        }, 8000); // 设置9秒定时器  
      } catch (error) {
        console.error('Error opening door:', error);
      } finally {
        isOpening.value = false; // 清除打开状态标记，无论成功或失败  
      }
    };
    onUnmounted(() => {
      clearTimeout(timerId); // 组件卸载时清除定时器，防止内存泄漏  
    });
</script>

<style scoped>
  .door-image {
    width: 50px;
    height: 50px;
    margin-left: 10px;
    margin-top: 0px;
  }
</style>